<?php
declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 委外模块控制器
 */
class Outsource extends BaseController
{
    /**
     * 获取委外厂商列表
     */
    public function getSupplierList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        
        $where = [];
        if (!empty($search)) {
            $where[] = ['supplier_name|contact_person|phone', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        $count = Db::name('outsource_supplier')->where($where)->count();
        $list = Db::name('outsource_supplier')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加委外厂商
     */
    public function addSupplier()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'supplier_name' => 'require',
            'contact_person' => 'require',
            'phone' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 检查厂商名称是否已存在
        $exists = Db::name('outsource_supplier')
            ->where('supplier_name', $data['supplier_name'])
            ->find();
            
        if ($exists) {
            return json(['code' => 400, 'msg' => '厂商名称已存在']);
        }
        
        $data['create_time'] = date('Y-m-d H:i:s');
        $result = Db::name('outsource_supplier')->insert($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新委外厂商
     */
    public function updateSupplier()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_name' => 'require',
            'contact_person' => 'require',
            'phone' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 检查厂商名称是否已存在（排除自身）
        $exists = Db::name('outsource_supplier')
            ->where('supplier_name', $data['supplier_name'])
            ->where('id', '<>', $data['id'])
            ->find();
            
        if ($exists) {
            return json(['code' => 400, 'msg' => '厂商名称已存在']);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        $result = Db::name('outsource_supplier')->update($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除委外厂商
     */
    public function deleteSupplier()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 检查是否有关联订单
        $hasOrder = Db::name('outsource_order')
            ->where('supplier_id', $id)
            ->find();
            
        if ($hasOrder) {
            return json(['code' => 400, 'msg' => '该厂商有关联的委外订单，无法删除']);
        }
        
        $result = Db::name('outsource_supplier')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取委外厂商详情
     */
    public function getSupplierDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $supplier = Db::name('outsource_supplier')->where('id', $id)->find();
        
        if (!$supplier) {
            return json(['code' => 400, 'msg' => '厂商不存在']);
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $supplier]);
    }
    
    /**
     * 获取委外订单列表
     */
    public function getOrderList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $supplier_id = Request::param('supplier_id', '');
        
        $where = [];
        if (!empty($search)) {
            $where[] = ['order_no', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        if ($supplier_id !== '') {
            $where[] = ['supplier_id', '=', $supplier_id];
        }
        
        $count = Db::name('outsource_order')->where($where)->count();
        $list = Db::name('outsource_order')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联厂商和产品信息
        foreach ($list as &$item) {
            $supplier = Db::name('outsource_supplier')->where('id', $item['supplier_id'])->find();
            $product = Db::name('product')->where('id', $item['product_id'])->find();
            $item['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
            $item['product_name'] = $product ? $product['product_name'] : '';
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加委外订单
     */
    public function addOrder()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'supplier_id' => 'require|number',
            'product_id' => 'require|number',
            'quantity' => 'require|number',
            'delivery_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 生成委外订单号
        $data['order_no'] = 'WW' . date('YmdHis') . rand(1000, 9999);
        $data['create_time'] = date('Y-m-d H:i:s');
        $result = Db::name('outsource_order')->insert($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新委外订单
     */
    public function updateOrder()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_id' => 'require|number',
            'product_id' => 'require|number',
            'quantity' => 'require|number',
            'delivery_date' => 'require|date',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        $result = Db::name('outsource_order')->update($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除委外订单
     */
    public function deleteOrder()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 检查是否有关联的发料记录
        $hasMaterial = Db::name('outsource_material')
            ->where('order_id', $id)
            ->find();
            
        if ($hasMaterial) {
            return json(['code' => 400, 'msg' => '该订单有关联的发料记录，无法删除']);
        }
        
        // 检查是否有关联的收货记录
        $hasReceipt = Db::name('outsource_receipt')
            ->where('order_id', $id)
            ->find();
            
        if ($hasReceipt) {
            return json(['code' => 400, 'msg' => '该订单有关联的收货记录，无法删除']);
        }
        
        $result = Db::name('outsource_order')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取委外订单详情
     */
    public function getOrderDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $order = Db::name('outsource_order')->where('id', $id)->find();
        
        if (!$order) {
            return json(['code' => 400, 'msg' => '订单不存在']);
        }
        
        // 关联厂商和产品信息
        $supplier = Db::name('outsource_supplier')->where('id', $order['supplier_id'])->find();
        $product = Db::name('product')->where('id', $order['product_id'])->find();
        $order['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        $order['product_name'] = $product ? $product['product_name'] : '';
        
        // 获取发料记录
        $materials = Db::name('outsource_material')
            ->where('order_id', $id)
            ->select()
            ->toArray();
            
        // 关联物料信息
        foreach ($materials as &$material) {
            $materialInfo = Db::name('material_category')->where('id', $material['material_id'])->find();
            $operator = Db::name('user')->where('id', $material['operator_id'])->find();
            $material['material_name'] = $materialInfo ? $materialInfo['material_name'] : '';
            $material['material_code'] = $materialInfo ? $materialInfo['material_code'] : '';
            $material['operator_name'] = $operator ? $operator['realname'] : '';
        }
        
        $order['materials'] = $materials;
        
        // 获取收货记录
        $receipts = Db::name('outsource_receipt')
            ->where('order_id', $id)
            ->select()
            ->toArray();
            
        // 关联操作员信息
        foreach ($receipts as &$receipt) {
            $operator = Db::name('user')->where('id', $receipt['operator_id'])->find();
            $receipt['operator_name'] = $operator ? $operator['realname'] : '';
        }
        
        $order['receipts'] = $receipts;
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $order]);
    }
    
    /**
     * 获取委外发料列表
     */
    public function getMaterialList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $order_id = Request::param('order_id', '');
        
        $where = [];
        if (!empty($search)) {
            // 通过订单号查询
            $orderIds = Db::name('outsource_order')
                ->where('order_no', 'like', "%{$search}%")
                ->column('id');
            if (!empty($orderIds)) {
                $where[] = ['order_id', 'in', $orderIds];
            }
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        if ($order_id !== '') {
            $where[] = ['order_id', '=', $order_id];
        }
        
        $count = Db::name('outsource_material')->where($where)->count();
        $list = Db::name('outsource_material')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联订单、物料和操作员信息
        foreach ($list as &$item) {
            $order = Db::name('outsource_order')->where('id', $item['order_id'])->find();
            $material = Db::name('material_category')->where('id', $item['material_id'])->find();
            $operator = Db::name('user')->where('id', $item['operator_id'])->find();
            $item['order_no'] = $order ? $order['order_no'] : '';
            $item['material_name'] = $material ? $material['material_name'] : '';
            $item['material_code'] = $material ? $material['material_code'] : '';
            $item['operator_name'] = $operator ? $operator['realname'] : '';
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加委外发料
     */
    public function addMaterial()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'order_id' => 'require|number',
            'material_id' => 'require|number',
            'quantity' => 'require|number',
            'issue_date' => 'require|date',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['create_time'] = date('Y-m-d H:i:s');
        
        Db::startTrans();
        try {
            $result = Db::name('outsource_material')->insert($data);
            
            // 如果状态为已确认，则更新库存
            if ($data['status'] == 2) {
                // 检查库存是否足够
                $material = Db::name('material_category')->where('id', $data['material_id'])->find();
                if ($material['current_quantity'] < $data['quantity']) {
                    throw new \Exception('物料 ' . $material['material_name'] . ' 库存不足');
                }
                
                // 减少库存
                Db::name('material_category')
                    ->where('id', $data['material_id'])
                    ->dec('current_quantity', $data['quantity'])
                    ->update(['last_update_time' => date('Y-m-d H:i:s')]);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '添加成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '添加失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新委外发料
     */
    public function updateMaterial()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'order_id' => 'require|number',
            'material_id' => 'require|number',
            'quantity' => 'require|number',
            'issue_date' => 'require|date',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        
        Db::startTrans();
        try {
            // 获取原发料记录
            $oldMaterial = Db::name('outsource_material')->where('id', $data['id'])->find();
            $oldStatus = $oldMaterial['status'];
            $oldQuantity = $oldMaterial['quantity'];
            
            // 更新发料记录
            $result = Db::name('outsource_material')->update($data);
            
            // 如果状态从未确认变为已确认，或者数量发生变化，则更新库存
            if (($oldStatus != 2 && $data['status'] == 2) || 
                ($oldStatus == 2 && $data['status'] == 2 && $oldQuantity != $data['quantity'])) {
                
                // 如果原状态为已确认，先恢复库存
                if ($oldStatus == 2) {
                    Db::name('material_category')
                        ->where('id', $data['material_id'])
                        ->inc('current_quantity', $oldQuantity)
                        ->update();
                }
                
                // 检查库存是否足够
                $material = Db::name('material_category')->where('id', $data['material_id'])->find();
                if ($material['current_quantity'] < $data['quantity']) {
                    throw new \Exception('物料 ' . $material['material_name'] . ' 库存不足');
                }
                
                // 减少库存
                Db::name('material_category')
                    ->where('id', $data['material_id'])
                    ->dec('current_quantity', $data['quantity'])
                    ->update(['last_update_time' => date('Y-m-d H:i:s')]);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '更新失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除委外发料
     */
    public function deleteMaterial()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        Db::startTrans();
        try {
            // 获取发料记录
            $material = Db::name('outsource_material')->where('id', $id)->find();
            
            // 删除发料记录
            $result = Db::name('outsource_material')->delete($id);
            
            // 如果状态为已确认，则恢复库存
            if ($material['status'] == 2) {
                Db::name('material_category')
                    ->where('id', $material['material_id'])
                    ->inc('current_quantity', $material['quantity'])
                    ->update(['last_update_time' => date('Y-m-d H:i:s')]);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取委外收货列表
     */
    public function getReceiptList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $order_id = Request::param('order_id', '');
        
        $where = [];
        if (!empty($search)) {
            // 通过订单号查询
            $orderIds = Db::name('outsource_order')
                ->where('order_no', 'like', "%{$search}%")
                ->column('id');
            if (!empty($orderIds)) {
                $where[] = ['order_id', 'in', $orderIds];
            }
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        if ($order_id !== '') {
            $where[] = ['order_id', '=', $order_id];
        }
        
        $count = Db::name('outsource_receipt')->where($where)->count();
        $list = Db::name('outsource_receipt')
            ->where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()
            ->toArray();
            
        // 关联订单和操作员信息
        foreach ($list as &$item) {
            $order = Db::name('outsource_order')->where('id', $item['order_id'])->find();
            $operator = Db::name('user')->where('id', $item['operator_id'])->find();
            $item['order_no'] = $order ? $order['order_no'] : '';
            $item['operator_name'] = $operator ? $operator['realname'] : '';
            if ($order) {
                $product = Db::name('product')->where('id', $order['product_id'])->find();
                $item['product_name'] = $product ? $product['product_name'] : '';
            } else {
                $item['product_name'] = '';
            }
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
    
    /**
     * 添加委外收货
     */
    public function addReceipt()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'order_id' => 'require|number',
            'receipt_date' => 'require|date',
            'quantity' => 'require|number',
            'quality_check' => 'require|number',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['create_time'] = date('Y-m-d H:i:s');
        $result = Db::name('outsource_receipt')->insert($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '添加成功']);
        } else {
            return json(['code' => 400, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 更新委外收货
     */
    public function updateReceipt()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'order_id' => 'require|number',
            'receipt_date' => 'require|date',
            'quantity' => 'require|number',
            'quality_check' => 'require|number',
            'operator_id' => 'require|number',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        $result = Db::name('outsource_receipt')->update($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除委外收货
     */
    public function deleteReceipt()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $result = Db::name('outsource_receipt')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
}
